<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>for...of循环</title>
</head>
<body>
    <h1>for...of循环</h1>
    <h2>一个数据结构只要部署了Symbol.iterator属性，就被视为具有iterator接口，就可以用for...of循环遍历它的成员</h2>

    <script>
        // 数组的for...of循环
        const arr = ['red', 'green', 'blue'];
        for (let value of arr) {
            console.log(value);
        }

        // Set和Map的for...of循环
        const set = new Set(['a', 'b', 'c']);
        for (let value of set) {
            console.log(value);
        }

        const map = new Map([
            ['name', '张三'],
            ['age', 20]
        ]);
        for (let [key, value] of map) {
            console.log(key + ': ' + value);
        }

        // 类数组对象的遍历
        const arrayLike = {
            length: 3,
            0: 'a',
            1: 'b',
            2: 'c',
            [Symbol.iterator]: Array.prototype[Symbol.iterator]
        };
        for (let item of arrayLike) {
            console.log(item);
        }

        // 对象的for...of循环
        const obj = {
            data: [1, 2, 3],
            *[Symbol.iterator]() {
                for (let item of this.data) {
                    yield item;
                }
            }
        };
        for (let value of obj) {
            console.log(value);
        }
    </script>
</body>
</html> 